import { contextBridge, ipcRenderer } from 'electron';

// --------- Expose some API to the Renderer process ---------
contextBridge.exposeInMainWorld('ipcRenderer', {
    on(...args: Parameters<typeof ipcRenderer.on>) {
        const [channel, listener] = args;
        return ipcRenderer.on(channel, (event, ...args) => listener(event, ...args));
    },
    off(...args: Parameters<typeof ipcRenderer.off>) {
        const [channel, ...omit] = args;
        return ipcRenderer.off(channel, ...omit);
    },
    send(...args: Parameters<typeof ipcRenderer.send>) {
        const [channel, ...omit] = args;
        return ipcRenderer.send(channel, ...omit);
    },
    invoke(...args: Parameters<typeof ipcRenderer.invoke>) {
        const [channel, ...omit] = args;
        return ipcRenderer.invoke(channel, ...omit);
    }

    // You can expose other APTs you need here.
    // ...
});

contextBridge.exposeInMainWorld('electronAPI', {
    openPrompt: (options: any) => ipcRenderer.invoke('open_prompt', options),
    readFile: (options: any) => ipcRenderer.invoke('read_file', options),
    selectDirectory: () => ipcRenderer.invoke('select_directory'),
    getLogFiles: (dirPath: string) => ipcRenderer.invoke('get_log_files', dirPath),
    readFileIncremental: (options: any) => ipcRenderer.invoke('read_file_incremental', options),
    readFileChunked: (options: any) => ipcRenderer.invoke('read_file_chunked', options),
    readFileTail: (options: any) => ipcRenderer.invoke('read_file_tail', options),
    readFileHead: (options: any) => ipcRenderer.invoke('read_file_head', options),
    selectJdkDirectory: () => ipcRenderer.invoke('select_jdk_directory'),
    selectJarFile: () => ipcRenderer.invoke('select_jar_file'),
    verifyJdkPath: (jdkPath: string) => ipcRenderer.invoke('verify_jdk_path', jdkPath),
    verifyJarFile: (jarPath: string) => ipcRenderer.invoke('verify_jar_file', jarPath),
    startJarService: (options: { jdkPath: string; jarPath: string }) => ipcRenderer.invoke('start_jar_service', options),
    stopJarService: () => ipcRenderer.invoke('stop_jar_service'),
    checkServiceHealth: () => ipcRenderer.invoke('check_service_health'),
    checkPortOccupied: (port: number) => ipcRenderer.invoke('check_port_occupied', port),
    
    // 版本更新相关 API
    fetchVersionInfo: (versionUrl: string) => ipcRenderer.invoke('fetch_version_info', versionUrl),
    getCachedVersion: () => ipcRenderer.invoke('get_cached_version'),
    saveVersionCache: (versionInfo: any) => ipcRenderer.invoke('save_version_cache', versionInfo),
    downloadFile: (options: { downloadUrl: string; savePath: string; fileName: string }) => 
        ipcRenderer.invoke('download_file', options),
    cancelDownload: () => ipcRenderer.invoke('cancel_download'),
    checkFileExists: (filePath: string) => ipcRenderer.invoke('check_file_exists', filePath),
    selectDownloadPath: () => ipcRenderer.invoke('select_download_path'),
    
    // 监听下载进度
    onDownloadProgress: (callback: (progress: any) => void) => {
        ipcRenderer.on('download-progress', (_, progress) => callback(progress));
    },
    offDownloadProgress: () => {
        ipcRenderer.removeAllListeners('download-progress');
    }
});

// --------- Preload scripts loading ---------
function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {
    return new Promise((resolve) => {
        if (condition.includes(document.readyState)) {
            resolve(true);
        } else {
            document.addEventListener('readystatechange', () => {
                if (condition.includes(document.readyState)) {
                    resolve(true);
                }
            });
        }
    });
}

const safeDOM = {
    append(parent: HTMLElement, child: HTMLElement) {
        if (!Array.from(parent.children).find((e) => e === child)) {
            return parent.appendChild(child);
        }
    },
    remove(parent: HTMLElement, child: HTMLElement) {
        if (Array.from(parent.children).find((e) => e === child)) {
            return parent.removeChild(child);
        }
    }
};

/**
 * YZJ-PRO 彩虹波动加载动画
 */
function useLoading() {
    const className = `yzj-pro-loading`;
    const styleContent = `
/* 彩虹背景自然浪潮动画 - 从左往右流动 */
@keyframes rainbow-wave {
  0% {
    background-position: -100% 0%;
  }
  25% {
    background-position: -25% 30%;
  }
  50% {
    background-position: 50% 70%;
  }
  75% {
    background-position: 125% 20%;
  }
  100% {
    background-position: 200% 50%;
  }
}

/* 波浪曲线变形动画 */
@keyframes wave-distortion {
  0% {
    transform: skewX(0deg) scaleY(1);
  }
  20% {
    transform: skewX(2deg) scaleY(1.05);
  }
  40% {
    transform: skewX(-1deg) scaleY(0.98);
  }
  60% {
    transform: skewX(1.5deg) scaleY(1.02);
  }
  80% {
    transform: skewX(-0.5deg) scaleY(1.01);
  }
  100% {
    transform: skewX(0deg) scaleY(1);
  }
}

/* 字母从右侧进入并旋转的动画 */
@keyframes letter-enter {
  0% {
    transform: translateX(200px) rotate(0deg);
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    transform: translateX(0) rotate(-360deg);
    opacity: 1;
  }
}

/* 字母从中间向左滚动消失的动画 */
@keyframes letter-exit {
  0% {
    transform: translateX(0) rotate(0deg);
    opacity: 1;
  }
  80% {
    opacity: 1;
  }
  100% {
    transform: translateX(-300px) rotate(-360deg);
    opacity: 0;
  }
}

.app-loading-wrap {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: 
    radial-gradient(ellipse at top, rgba(255,255,255,0.1) 0%, transparent 50%),
    linear-gradient(120deg, #ff0000, #ff7f00, #ffff00, #00ff00, #0000ff, #4b0082, #9400d3, #ff0000, #ff7f00),
    radial-gradient(ellipse at bottom, rgba(255,255,255,0.05) 0%, transparent 70%);
  background-size: 100% 100%, 600% 150%, 100% 100%;
  animation: 
    rainbow-wave 12s ease-in-out infinite,
    wave-distortion 8s ease-in-out infinite;
  z-index: 9;
  overflow: hidden;
}

.app-loading-wrap::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(45deg, 
    transparent 20%, 
    rgba(255,255,255,0.1) 40%, 
    transparent 60%, 
    rgba(255,255,255,0.05) 80%, 
    transparent 100%);
  background-size: 200% 200%;
  animation: wave-overlay 15s ease-in-out infinite reverse;
  pointer-events: none;
}

/* 波浪叠加层动画 */
@keyframes wave-overlay {
  0% {
    background-position: -50% -50%;
    transform: rotate(0deg);
  }
  33% {
    background-position: 50% 150%;
    transform: rotate(1deg);
  }
  66% {
    background-position: 150% -50%;
    transform: rotate(-0.5deg);
  }
  100% {
    background-position: 250% 150%;
    transform: rotate(0deg);
  }
}

.${className} {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  font-family: 'Arial Black', Arial, sans-serif;
  font-size: 4rem;
  font-weight: bold;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}

.${className} .letter {
  color: white;
  opacity: 0;
  transform: translateX(200px);
  animation-fill-mode: forwards;
}

/* 入场动画 */
.${className}.entering .letter:nth-child(1) { animation: letter-enter 0.8s ease-out 0.1s forwards; }
.${className}.entering .letter:nth-child(2) { animation: letter-enter 0.8s ease-out 0.3s forwards; }
.${className}.entering .letter:nth-child(3) { animation: letter-enter 0.8s ease-out 0.5s forwards; }
.${className}.entering .letter:nth-child(4) { animation: letter-enter 0.8s ease-out 0.7s forwards; }
.${className}.entering .letter:nth-child(5) { animation: letter-enter 0.8s ease-out 0.9s forwards; }
.${className}.entering .letter:nth-child(6) { animation: letter-enter 0.8s ease-out 1.1s forwards; }
.${className}.entering .letter:nth-child(7) { animation: letter-enter 0.8s ease-out 1.3s forwards; }

/* 退场动画 */
.${className}.exiting .letter:nth-child(1) { animation: letter-exit 0.8s ease-in 0.1s forwards; }
.${className}.exiting .letter:nth-child(2) { animation: letter-exit 0.8s ease-in 0.3s forwards; }
.${className}.exiting .letter:nth-child(3) { animation: letter-exit 0.8s ease-in 0.5s forwards; }
.${className}.exiting .letter:nth-child(4) { animation: letter-exit 0.8s ease-in 0.7s forwards; }
.${className}.exiting .letter:nth-child(5) { animation: letter-exit 0.8s ease-in 0.9s forwards; }
.${className}.exiting .letter:nth-child(6) { animation: letter-exit 0.8s ease-in 1.1s forwards; }
.${className}.exiting .letter:nth-child(7) { animation: letter-exit 0.8s ease-in 1.3s forwards; }

/* 等待状态时的轻微浮动效果 */
.${className}.waiting .letter {
  animation: none;
  opacity: 1;
  transform: translateX(0) rotate(0deg);
}

/* 退场状态初始设置 */
.${className}.exiting .letter {
  opacity: 1;
  transform: translateX(0) rotate(0deg);
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
}

.${className}.waiting .letter:nth-child(1) { animation: float 2s ease-in-out 0.1s infinite; }
.${className}.waiting .letter:nth-child(2) { animation: float 2s ease-in-out 0.3s infinite; }
.${className}.waiting .letter:nth-child(3) { animation: float 2s ease-in-out 0.5s infinite; }
.${className}.waiting .letter:nth-child(4) { animation: float 2s ease-in-out 0.7s infinite; }
.${className}.waiting .letter:nth-child(5) { animation: float 2s ease-in-out 0.9s infinite; }
.${className}.waiting .letter:nth-child(6) { animation: float 2s ease-in-out 1.1s infinite; }
.${className}.waiting .letter:nth-child(7) { animation: float 2s ease-in-out 1.3s infinite; }
    `;

    const oStyle = document.createElement('style');
    const oDiv = document.createElement('div');

    oStyle.id = 'app-loading-style';
    oStyle.innerHTML = styleContent;
    oDiv.className = 'app-loading-wrap';
    oDiv.innerHTML = `
    <div class="${className} entering" id="yzj-pro-text">
      <span class="letter">Y</span>
      <span class="letter">Z</span>
      <span class="letter">J</span>
      <span class="letter">-</span>
      <span class="letter">P</span>
      <span class="letter">R</span>
      <span class="letter">O</span>
    </div>
  `;

    let animationCycle: number;
    let isAnimating = false;

    function startAnimationCycle() {
        if (isAnimating) return;
        isAnimating = true;

        const textElement = document.getElementById('yzj-pro-text');
        if (!textElement) return;

        // 开始入场动画
        textElement.className = `${className} entering`;

        // 2秒后切换到等待状态（所有字母都已进入）
        setTimeout(() => {
            textElement.className = `${className} waiting`;

            // 7秒等待后开始退场动画
            setTimeout(() => {
                textElement.className = `${className} exiting`;

                // 退场动画完成后重新开始循环
                setTimeout(() => {
                    isAnimating = false;
                    animationCycle = requestAnimationFrame(startAnimationCycle);
                }, 2500); // 退场动画持续时间（0.8s动画 + 1.3s延迟 + 0.4s缓冲）
            }, 7000); // 等待7秒
        }, 2000); // 入场动画持续时间
    }

    return {
        appendLoading() {
            safeDOM.append(document.head, oStyle);
            safeDOM.append(document.body, oDiv);
            // 启动动画循环
            setTimeout(startAnimationCycle, 100);
        },
        removeLoading() {
            if (animationCycle) {
                cancelAnimationFrame(animationCycle);
            }
            isAnimating = false;
            safeDOM.remove(document.head, oStyle);
            safeDOM.remove(document.body, oDiv);
        }
    };
}

// ----------------------------------------------------------------------

const { appendLoading, removeLoading } = useLoading();
domReady().then(appendLoading);

window.onmessage = (ev) => {
    ev.data.payload === 'removeLoading' && removeLoading();
};

setTimeout(removeLoading, 1000);
